# -*- mode: python -*-
###
#
# (c) 2000-2007 Wijnand Modderman <wijnand at tehmaze dot com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#   * Redistributions of source code must retain the above copyright notice,
#     this list of conditions, and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright notice,
#     this list of conditions, and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#   * Neither the name of the author of this software nor the name of
#     contributors to this software may be used to endorse or promote products
#     derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###

__revision__ = '$Hg:$'

# system imports

# DDB imports
from ddb.log import log
from ddb.tools import humanSize, syntax
from ddb.register import register
from raw.urlcache import URLCacher

# Twisted imports
from twisted.web import client

# DDB exports
EXPORT=['Http']

class Http:
    HIDDEN=['httppageinfo']

    def __init__(self):
        self.reg = register.init(self)

    def httppageinfo(self, event):
        """this command is not intended for user calling."""
        if not hasattr(event, 'pageInfo'):
            event.reply(syntax())
            return
        context = self.reg.eventContext(event)
        enabled = self.reg.get('snarf', *context)
        if not enabled or not enabled[0]:
            return
        scheme, host, port, path = client._parse(event.args)
        reply = '%s (%s on %s)' % (event.pageInfo['title'], humanSize('bytes', event.pageInfo['size']), host)
        event.reply(reply)

    def httpinfo(self, event):
        """[-s] <[hostname]> [port]

        Retreive information about the webserver on <url>. Use the -s flag to enable SSL. The port
        defaults to 80, or 443 for SSL."""
        args = event.args.split()
        ssl  = False
        port = 80
        if args[0].lower() == '-s':
            ssl  = True
            port = 443
            args = args[1:]
        if len(args) == 2:
            try:
                port = int(args[1])
            except:
                port = -1
        if not args or len(args) > 2 or port == -1:
            event.reply(syntax())
            return
        schema = 'http://'
        if ssl:
            schema = 'https://'
        url = '%s%s:%d' % (schema, args[0], port)
        event.message = url
        URLCacher._onMessage(event, self._httpinfo, self._httperr)

    def _httpinfo(self, headers, url, event):
        if not headers:
            event.reply('could not fetch %s' % url)
            return
        keep = ['server', 'content-type']
        kept = []
        #for key in keep:
        for key in headers.keys():
            if headers.has_key(key):
                for value in headers[key]:
                    kept.append('%s = %s' % (key, value))
        if not kept:
            event.reply('no interesting headers found on %s' % url)
        else:
            event.reply('headers on %s: %s' % (url, ', '.join(kept)))

    def _httperr(self, failure, url, event):
        event.reply('failed to fetch info about %s: %s' % (url, failure.getErrorMessage()))

    def snarf(self, event):
        """[on|off]

        Turns auto-snarfing of URL information on or off. """
        if event.args and not event.args.lower() in ['on', 'off']:
            event.reply(syntax())
            return
        elif not event.args:
            context  = self.reg.eventContext(event)
            try:
                snarfing = self.reg.get('snarf', *context)
            except Exception,e:
                log.err()
            event.reply(str(snarfing))
        else:
            if event.args.lower() == 'off':
                enabled = False
            else:
                enabled = True
            context = self.reg.eventContext(event)
            self.reg.set('snarf', enabled, *context)
            event.reply('snarf is now %s' % event.args)    

# vim:ts=4:sw=4:et:
